package net.neptech.service.impl;

import net.neptech.mapper.MenuMapper;
import net.neptech.service.MenuService;
import net.neptech.service.PermissionService;
import net.neptech.service.RoleService;
import net.neptech.utils.SecurityUtils;
import net.neptech.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: liyuxiang
 * @Date: 2025/8/14 13:48
 * @Description: TODO
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    MenuMapper menuMapper;

    @Override
    public Set<String> getRolePermission() {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(SecurityUtils.getUserId()));
        }
        return roles;
    }

    @Override
    public Set<String> getMenuPermission() {

        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            perms.add("*:*:*");
        } else {

            Set<String> roles = getRolePermission();
            if (!CollectionUtils.isEmpty(roles)) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (String role : roles) {
                    List<String> rolePerms = menuMapper.selectMenuPermsByRoleName(role);
                    if (!CollectionUtils.isEmpty(rolePerms)) {
                        for (String perm : rolePerms) {
                            if (StringUtils.isNotEmpty(perm)) {
                                perms.addAll(Arrays.asList(perm.trim().split(",")));
                            }
                        }
                    }
                }
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(SecurityUtils.getUserId()));
            }
        }
        return perms;
    }
}
